package com.app.filter;

import com.alibaba.fastjson.JSON;
import com.app.common.BaseVo;
import com.app.common.Const;
import com.app.common.ResultCode;
import com.app.utils.CacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author SmallPlume
 * @title: RequestGatewayFilter
 * @projectName applet
 * @description: TODO
 * @date 2019/10/13 23:15
 */
@Component
public class AuthSignatureFilter implements GlobalFilter, Ordered {

    @Autowired
    private CacheUtil cacheUtil;

    /**
     * 网关是非常重要的,在这里不让写过多代码,整个流程下来最好不要超过30ms，
     * 别的需要的数据可以自己根据需求去取
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取URI
        String url = exchange.getRequest().getURI().toString();
        // 请求路径
        String address = exchange.getRequest().getRemoteAddress().toString();
        // 获取token
        String token = exchange.getRequest().getHeaders().getFirst(Const.TOKEN_NAME);
        // 获取请求端
        String terminalId = exchange.getRequest().getHeaders().getFirst(Const.TERMINALID);
        // 放权URL
        String[] devolutionPath = {"sys/login", "callback/pay"};
        for (String path : devolutionPath) {
            if (url.contains(path)) return chain.filter(exchange);
        }
        ServerHttpResponse response = exchange.getResponse();
        // 所有的请求不一定都放在header，有些是在URL或body中
        if (token == null) {
            // 从URL中获取
            token = exchange.getRequest().getQueryParams().getFirst("token");
            if (token == null) {
                // TODO 从body中获取参数
            }
        }
        if (token == null) {
            return returnResult(new BaseVo(ResultCode.ERR_MISS_PARAM.getCode(), "toke为空或请求端为空"), response);
        }
        // 进行校验
        /*if (cacheUtil.hasKey(token)) {
            return chain.filter(exchange);
        }*/
        if (token.equals("10086")) {
            return chain.filter(exchange);
        }
        return returnResult(new BaseVo(ResultCode.UNAUTH.getCode(), ResultCode.UNAUTH.getInfo()), response);
    }

    private Mono<Void> returnResult(BaseVo baseVo, ServerHttpResponse response) {
        byte[] datas = JSON.toJSONString(baseVo).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(datas);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
